#include "csvexporter.h"

CsvExporter::CsvExporter(QObject *parent) : QObject(parent)
{
}
void CsvExporter::setHeader(const QStringList &header)
{
    m_header = header;
}

void CsvExporter::addRow(const QStringList &row)
{
    m_data.append(row);
}

void CsvExporter::clearData()
{
    m_header.clear();
    m_data.clear();
}

bool CsvExporter::exportToFile(const QString &filePath, const QString &separator)
{
    QFile file(filePath);
    if (!file.open(QIODevice::Append | QIODevice::Text)) {
        //QMessageBox::critical(nullptr, "导出失败", "无法打开文件: " + filePath);
        return false;
    }

    QTextStream out(&file);
    out.setCodec("UTF-8");

    // 写入表头
    if (!m_header.isEmpty()) {
        out << m_header.join(separator) << "\n";
    }

    // 写入数据
    for (const auto &row : m_data) {
        QStringList escapedRow;
        for (const QString &value : row) {
            // 处理包含分隔符或引号的值
            QString escapedValue = value;
            if (escapedValue.contains(separator) || escapedValue.contains("\"")) {
                escapedValue = "\"" + escapedValue.replace("\"", "\"\"") + "\"";
            }
            escapedRow.append(escapedValue);
        }
        out << escapedRow.join(separator) << "\n";
    }

    file.close();
    return true;
}
